/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fait.ferm.persists;

import fait.ferm.global.Glob;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Greg
 */
public class Fine extends PersistsObject {
    public int credit_id;
    public Date date_arrears;
    public double amount_arrears;
    
    public Fine() {
        super();
        table = "fine";
    }
    
    public Fine(int pId) throws Exception {
        super(pId);
        table = "fine";
        load();
    }
    
    @Override
    public void load() throws Exception {
        boolean notSuccessfully=true;
		if(id==-1) {
			throw new Exception("Объект "+table+" отсутствует в базе");
		}	
		try (Statement st = con.createStatement()) {
			String q = "SELECT credit_id, date_arrears, amount_arrears FROM "+table+" WHERE id = " + id;
			ResultSet rs = st.executeQuery(q);
			if(rs.next()){
				notSuccessfully=false;
                credit_id = rs.getInt("credit_id");
                date_arrears = Date.valueOf(rs.getString("date_arrears"));
                amount_arrears = rs.getDouble("amount_arrears");
			}
			rs.close();
		}
		if(notSuccessfully) {
			throw new Exception("Объект "+table+" не загружен");
        }
    }

    @Override
    protected void update() throws SQLException {
        try (Statement st = con.createStatement()) {
			String q = "UPDATE "+table+" SET " + 
                    "credit_id" + credit_id + ", " +
                    "amount_arrears" + amount_arrears + ", " +
                    "date_arrears" + date_arrears.toString() + " " +
					"WHERE id = " + id;
			st.executeUpdate(q);
		}
    }

    @Override
    protected void createNew() throws SQLException, Exception {
        try (Statement st = con.createStatement()) {
			String q = "INSERT INTO " + table + " (credit_id, date_arrears, amount_arrears) VALUES("+
						credit_id + ","+
						amount_arrears + ","+
                        date_arrears.toString() +
					")";
			st.executeUpdate(q);
			q="SELECT seq FROM sqlite_sequence WHERE name = '"+table+"'";
			ResultSet rs = st.executeQuery(q);
			if(rs.next()){
				id = rs.getInt("seq");
			}
			rs.close();
		}
    }
    
}
